package com.hngy.xpq.android_practice.ui.home;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;

import com.hngy.xpq.android_practice.MerchantActivity;
import com.hngy.xpq.android_practice.R;
import com.hngy.xpq.android_practice.adapter.CommAdapter;
import com.hngy.xpq.android_practice.assets.XpqIcoMoon;
import com.hngy.xpq.android_practice.assets.XpqIcoMoonUtils;
import com.hngy.xpq.android_practice.bean.Comm;
import com.hngy.xpq.android_practice.bean.Orders;
import com.hngy.xpq.android_practice.bean.Recording;
import com.hngy.xpq.android_practice.database.SQLiteComm;
import com.hngy.xpq.android_practice.database.SQLiteRecording;
import com.hngy.xpq.android_practice.http.TcpClient;
import com.hngy.xpq.android_practice.utils.Order;

import java.util.ArrayList;
import java.util.List;

public class SearchComm extends AppCompatActivity {

    SQLiteComm sqLiteComm;
    SQLiteRecording sqLiteRecording,recording;
    EditText search_name;
    Button bin;
    GridView list;
    ListView grid;
    List<Comm> lists;
    List<Recording> recordings;
    Recording r;
    CommAdapter adapter;
    SharedPreferences comm,history,main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comm_search_home);

        search_name = findViewById(R.id.comm_search_name);
        bin = findViewById(R.id.bin_search);
        list = findViewById(R.id.search_comm);
        grid = findViewById(R.id.search_history);

        //历史搜索存储
        history = super.getSharedPreferences("history",MODE_PRIVATE);
        HistorySearch();
        //映射文字图标
        bin.setText(XpqIcoMoon.COMM);
        XpqIcoMoonUtils.setIOC(bin);
        //调用本地存储
        comm = super.getSharedPreferences("comm",MODE_PRIVATE);
        main = super.getSharedPreferences("main",MODE_PRIVATE);

        //搜索、搜索记录存储
        bin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(search_name.getText())){
                    Toast.makeText(SearchComm.this,"搜索不能为空!!",Toast.LENGTH_SHORT).show();
                } else {
                    String index = history.getString("history","");
                    //记录搜索历史
                    if (index.length() != 0){
                        String[] strins = index.split("\\-");
                        int a = 0;
                        for (int i = 0 ; i < strins.length ; i++){     //搜索记录数据查重
                            if (strins[i].equals(search_name.getText().toString())){
                                a = 1;
                            }
                        }
                        if (a == 0){
                            index = index + "-" + search_name.getText().toString();
                        }
                    } else {
                        index = search_name.getText().toString();
                    }
                    grid.setAdapter(null);
                    SharedPreferences.Editor editor = history.edit();
                    editor.putString("history",index);
                    editor.commit();
                    //搜索方法
                    InitData();
                }
            }
        });

        //通过listview的触发事件进行点餐
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchComm.this,User_Comm.class);
                Comm c = lists.get(position);
                SharedPreferences.Editor editor = comm.edit();
                editor.putString("name",c.getComm_name());
                editor.putString("price",c.getComm_price());
                editor.putString("phone",c.getComm_phone());
                editor.putString("comm_name",c.getMerchant_name());
                editor.putString("position", String.valueOf(position));
                editor.putString("math",search_name.getText().toString());
                editor.putString("status",c.getStatus());
                editor.commit();
                //浏览查重
                if (recordings != null){
                    recordings.clear();
                }
                recordings = sqLiteRecording.recordingQuery(main.getString("name",""));
                int index = 0;
                for (int x = 0 ; x < recordings.size() ; x++ ){
                    if (recordings.get(x).getRecording_name().equals(c.getComm_name())){
                        index = 1;
                    }
                }
                //添加浏览记录
                if ( index == 0 ){
                    r = new Recording();
                    r.setMerchant_name(c.getMerchant_name());
                    r.setRecording_name(c.getComm_name());
                    r.setUser_name(main.getString("name",""));
                    r.setLikes("recording");
                    if (sqLiteRecording.recording_add(r)){
                        Log.i("保存成功","");
                    } else {
                        Log.i("保存失败","");
                    }
                }
                startActivity(intent);
            }
        });
    }

    private void inforClientNameAndDow() {    //因为PC和Android互通，所有每次登录需要验证账号信息是否改动
        String information = "DL001//" + main.getString("name","") + "//" + main.getString("key","");
        String a = new TcpClient().Transits(information);
        if (a.equals("登录失败")) {
            IndexToast("账号发生改变，请重新登录");
        }
    }

    //未进行搜索状态下的界面布局，当记录数量达到五个时，自动加入更多、删除功能
    private void HistorySearch() {
        if (TextUtils.isEmpty(search_name.getText())){
            String histories = history.getString("history","");
            final String[] strings = histories.split("\\-");
            final int a = strings.length;
            //使用系统自带的适配器
            List<String> data = new ArrayList<>();
            for (int i = 0 ; i < strings.length ; i++){
                if (i > 4){
                    data.add("更多搜索记录...");
                    data.add("清除搜索历史");
                    break;
                } else {
                    data.add(strings[i]);
                }
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(  this,R.layout.item_history,R.id.text,data);
            grid.setAdapter(adapter);
            grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {     //通过触发事件搜索商品
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 6 ){
                        SharedPreferences.Editor editor = history.edit();
                        editor.putString("history","");
                        editor.commit();
                        parent.setAdapter(null);
                    } else {
                        search_name.setText(strings[position]);
                        parent.setAdapter(null);
                        InitData();
                    }
                }
            });
        }
    }

    //初始化数据库方法
    private void InitData() {
        sqLiteComm = new SQLiteComm(this);
        sqLiteRecording = new SQLiteRecording(this);
        showQueryComm();
    }

    //数据通过适配器展示出来
    private void showQueryComm() {
        if (lists != null){
            lists.clear();
        }
        lists = sqLiteComm.CommSearch(search_name.getText().toString());
        adapter = new CommAdapter(this,lists);
        list.setAdapter(adapter);
    }

    //判断接收
    @Override
    protected void onActivityResult(int requestCode,int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==2){
            showQueryComm();
        }
    }

    public void IndexToast(String text){
        Toast.makeText(SearchComm.this,text,Toast.LENGTH_SHORT).show();
    }
}